package com.cnswhy.cloud.server.comsumer.receiver.split;


import com.cnswhy.cloud.common.logging.constant.MDCConstant;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.mq.UpdateCustomerSplitMQ;
import com.cnswhy.cloud.server.comsumer.event.split.UpdateCustomerSplitEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class UpdateCustomerSplitReceiver {

    @Autowired(required = false)
    private List<UpdateCustomerSplitEvent> events;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = AmqpExchange.UPDATE_CUSTOMER_SPLIT_MESSAGE + AmqpExchange.QUEUE),
            exchange = @Exchange(value = AmqpExchange.UPDATE_CUSTOMER_SPLIT_MESSAGE, type = ExchangeTypes.FANOUT)
    ))
    public void sendMessage(UpdateCustomerSplitMQ updateCustomerSplitMQ) {
        if(StringUtils.isNotBlank(updateCustomerSplitMQ.getTraceId())){
            MDC.put(MDCConstant.LOG_TRACE_ID, updateCustomerSplitMQ.getTraceId());
        }

        if (events != null) {
            for (UpdateCustomerSplitEvent event : events) {
                try {
                    event.update(updateCustomerSplitMQ);
                } catch (Exception e) {
                    log.error("消息发送失败", e);
                }
            }
        }
    }
}
